import os
from flask import Blueprint, render_template, request, send_from_directory, jsonify, url_for, current_app
from werkzeug.utils import secure_filename
from app.utils import get_merger, get_converter, system_cleanup, validate_filename

routes = Blueprint('routes', __name__)


@routes.route('/')
def index():
    """首页，展示上传表单"""
    print(f"Template folder: {current_app.template_folder}")  # 使用 current_app 替代 app
    return render_template('index.html')


@routes.route('/merge', methods=['POST'])
def merge_pdf_route():
    """处理PDF合并请求"""
    merger = get_merger()
    try:
        files = request.files.getlist('pdfFiles')
        # 验证至少选择两个文件
        if len(files) < 2:
            return jsonify({'success': False, 'message': '请选择至少两个PDF文件进行合并'}), 400
        
        custom_name = secure_filename(request.form.get('outputFilename', 'merged.pdf'))
        output_path = merger.merge(files, custom_name)
        merger.cleanup()  # 清理合并产生的临时文件
        return jsonify({
            'success': True,
            'downloadLink': url_for('routes.download_merged', filename=os.path.basename(output_path))
        })
    except Exception as e:
        merger.cleanup()
        return jsonify({'success': False, 'message': f'合并失败: {str(e)}'}), 500


@routes.route('/download/<filename>')
def download_merged(filename):
    """提供合并后的PDF文件下载"""
    # 修改为从output目录下载文件
    output_dir = os.path.join(os.getcwd(), 'output')
    return send_from_directory(output_dir, filename, as_attachment=True)


@routes.route('/convert', methods=['POST'])
def convert_pdf_to_word():
    """处理PDF转Word请求"""
    converter = get_converter()
    try:
        if 'pdfFile' not in request.files:
            raise ValueError("未选择文件")
            
        pdf_file = request.files['pdfFile']
        if pdf_file.filename == '':
            raise ValueError("文件名为空")
            
        custom_name = secure_filename(request.form.get('outputFilename', 'converted.docx'))
        if not validate_filename(custom_name, ['.docx']):
            return jsonify({'success': False, 'message': '文件名必须为.docx格式'}), 400
        output_path = converter.convert_to_word(pdf_file, custom_name)
        return jsonify({
            'success': True,
            'downloadLink': url_for('routes.download_merged', filename=os.path.basename(output_path))
        })
    except Exception as e:
        return jsonify({'success': False, 'message': f'转换失败: {str(e)}'}), 500


def teardown(exception):
    """应用关闭时执行系统级清理"""
    system_cleanup()


# 在文件末尾添加导出
__all__ = ['routes', 'teardown']
